package me.zhengjie.timing.plc;

import lombok.RequiredArgsConstructor;
import me.zhengjie.WcsReport.WcsReportService;
import me.zhengjie.agvSend.AgvSendService;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.entity.*;
import me.zhengjie.pojo.vo.TestVo;
import me.zhengjie.sqlservice.*;
import me.zhengjie.tcp.FluentFrameTCPA;
import me.zhengjie.tcp.FluentFrameTCPB;
import me.zhengjie.util.state.MaterialStatus;
import me.zhengjie.util.state.TaskStatus;
import me.zhengjie.util.state.TaskType;
import me.zhengjie.utility.IdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class FluentFrameTiming {
    private static final Logger fluentFrame = LoggerFactory.getLogger("fluentFrame");

    private final WcsFluentFrameConfigService wcsFluentFrameConfigService;

    private final FluentFrameTCPA fluentFrameTCPA;

    private final FluentFrameTCPB fluentFrameTCPB;

    private final WcsReportService wcsReportService;

    private final WcsInboundMissionService wcsInboundMissionService;

    private final AgvSendService agvSendService;

    private final WcsOutboundMissionService wcsOutboundMissionService;

    private final IdWorker idWorker;

    private final WcsFluentFrameOutboundDetailsService wcsFluentFrameOutboundDetailsService;

    private final WcsFluentFrameOutboundDetailsHistoryService wcsFluentFrameOutboundDetailsHistoryService;

    private final NestingMiddleTableService nestingMiddleTableService;

    @Transactional
//    @Scheduled(fixedDelay = 1000)
    public void fluentFrame() {
        List<WcsOutboundMission> wcsOutboundMissions = wcsOutboundMissionService.selectTask(TaskStatus.Task_create.getStatus(), TaskType.WORKBIN.getStatus());
        fluentFrame.info("流利架查询出库任务数据：{}", wcsOutboundMissions);
        for (WcsOutboundMission wcsOutboundMission : wcsOutboundMissions) {
            //出库任务终点工位
            String destination = wcsOutboundMission.getDestination();
            String containerCode = wcsOutboundMission.getContainerCode();
            //根据出库任务工位查询，查询对应流利架、
            List<WcsFluentFrameConfig> wcsFluentFrameConfigList = wcsFluentFrameConfigService.selectStorageRegion(destination);
            if (!wcsFluentFrameConfigList.isEmpty()) {
                for (WcsFluentFrameConfig wcsFluentFrameConfig : wcsFluentFrameConfigList) {
                    Integer outboundStorageSizeAddress = wcsFluentFrameConfig.getOutboundStorageSizeAddress();
                    String storageCode = wcsFluentFrameConfig.getStorageCode();
                    String storageRegion = wcsFluentFrameConfig.getStorageRegion();
                    Integer unitId = wcsFluentFrameConfig.getUnit_id();
                    Integer size = wcsFluentFrameConfig.getSize();
                    Integer cylinder = wcsFluentFrameConfig.getCylinder();
                    String region = wcsFluentFrameConfig.getRegion();
                    Integer threeReturnResult = wcsFluentFrameConfig.getThreeReturnResult();
                    Integer cylinderStatus = 0;
                    //查询气缸状态对接上层
                    if (TaskType.FLUENT_FRAME_A.getMessage().equals(region)) {
                        //A區域
                        cylinderStatus = fluentFrameTCPA.readHoldingRegisters(cylinder, unitId);
                    } else if (TaskType.FLUENT_FRAME_B.getMessage().equals(region)) {
                        //B區域
                        cylinderStatus = fluentFrameTCPA.readHoldingRegisters(cylinder, unitId);
                    }
                    if (cylinderStatus == 1) {
                        Integer storageSize = 3;
                        storageSize = storageSize - size;
                        //查询2楼料箱状态为0的入库任务到该储位
                        if (storageSize > 0) {
                            List<WcsOutboundMission> wcsOutboundMissionList = wcsOutboundMissionService.selectStatusAndDestinationAndContainerTypePage(TaskStatus.Task_create, storageRegion, TaskType.WORKBIN.getStatus(), storageSize);
                            if (!wcsOutboundMissionList.isEmpty()) {
                                //下发agv任务，修改状态为1
                                for (WcsOutboundMission outboundMission : wcsOutboundMissionList) {
                                    String outboundCode = outboundMission.getOutboundCode();
                                    Integer id = outboundMission.getId();
                                    AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                    //todo 任务类型，根据现场情况来定
                                    agvTaskSubmitDto.setTaskType(TaskType.PF_FMR_COMMON.getMessage());
                                    ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                    TargetRoute targetRoute = new TargetRoute();
                                    TargetRoute targetRoutes = new TargetRoute();
                                    //添加起点
                                    targetRoute.setSeq(0);
                                    targetRoute.setType(TaskType.STORAGE.getMessage());
                                    targetRoute.setCode(outboundMission.getSource());
                                    //添加终点
                                    targetRoutes.setSeq(1);
                                    targetRoutes.setType(TaskType.SITE.getMessage());
                                    targetRoutes.setCode(storageCode);
                                    targetRouteList.add(targetRoute);
                                    targetRouteList.add(targetRoutes);
                                    agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                    String deliveryCode = String.valueOf(outboundCode);
                                    agvTaskSubmitDto.setRobotTaskCode(deliveryCode);
                                    agvTaskSubmitDto.setInitPriority(outboundMission.getPriority());
                                    String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                    if (taskCode != null) {
                                        fluentFrameTCPA.writeWithRetry(threeReturnResult, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        //记录载具出库位置到哪个流利架
                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = new WcsFluentFrameOutboundDetails();
                                        wcsFluentFrameOutboundDetails.setContainerCode(containerCode);
                                        wcsFluentFrameOutboundDetails.setStorageCode(storageCode);
                                        wcsFluentFrameOutboundDetails.setIsNest(0);
                                        wcsFluentFrameOutboundDetailsService.insertFluentFrameOutboundDetails(wcsFluentFrameOutboundDetails);
                                        size++;
                                        //修改流利架数量
                                        wcsFluentFrameConfigService.updateSize(id, size);
                                        //修改任务状态已发送
                                        boolean b = wcsInboundMissionService.updateMissionStatus(outboundCode, TaskStatus.task_send.getStatus());
                                        if (!b) {
                                            fluentFrame.error("出库下发任务，修改数据库失败");
                                            throw new RuntimeException("出库下发任务，修改数据库失败");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //查询所有流利架
        List<WcsFluentFrameConfig> wcsFluentFrameConfigList = wcsFluentFrameConfigService.selectAll();
        if (!wcsFluentFrameConfigList.isEmpty()) {
            for (WcsFluentFrameConfig wcsFluentFrameConfig : wcsFluentFrameConfigList) {
                Integer singleOrDouble = wcsFluentFrameConfig.getSingleOrDouble();
                Integer size = wcsFluentFrameConfig.getSize();
                if (singleOrDouble == 2) {
                    //双层流利架
                    //查询气缸地址位，当前状态
                    Integer id = wcsFluentFrameConfig.getId();
                    Integer cylinder = wcsFluentFrameConfig.getCylinder();
                    String region = wcsFluentFrameConfig.getRegion();
                    Integer unitId = wcsFluentFrameConfig.getUnit_id();
                    Integer sortingAddress = wcsFluentFrameConfig.getSortingAddress();
                    Integer sortingResultAddress = wcsFluentFrameConfig.getSortingResultAddress();
                    Integer mode = wcsFluentFrameConfig.getMode();
                    String storageRegion = wcsFluentFrameConfig.getStorageRegion();
                    String storageCode = wcsFluentFrameConfig.getStorageCode();
                    String sortingContainerCode = wcsFluentFrameConfig.getSortingContainerCode();
                    Integer threeReturnResult = wcsFluentFrameConfig.getThreeReturnResult();
                    //判断当前是A区还是B区
                    if (TaskType.FLUENT_FRAME_A.getMessage().equals(region)) {
                        Integer cylinderStatus = fluentFrameTCPA.readHoldingRegisters(cylinder, unitId);
                        Integer sortingStatus = fluentFrameTCPA.readHoldingRegisters(sortingAddress, unitId);
                        //判断气缸当前状态,入库
                        if (cylinderStatus == 2) {
                            if (sortingStatus == 1) {
                                //分拣区有货，获取读码结果
                                Integer sortingReadAddress = wcsFluentFrameConfig.getSortingReadAddress();
                                String palletCode = fluentFrameTCPA.readHoldingRegistersString(sortingReadAddress, unitId);
                                //是空箱入库还是正常入库
                                if (mode == 0) {
                                    //空箱入库
                                    //查詢嵌套信息不能存在该物料
                                    List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(palletCode);
                                    if (!nestingMiddleTables.isEmpty()) {
                                        fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_NG.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    } else {
                                        InboundIsCodeExistDto inboundIsCodeExist = new InboundIsCodeExistDto();
                                        inboundIsCodeExist.setContainerCode(palletCode);
                                        inboundIsCodeExist.setNest(false);
                                        boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExist);
                                        if (b) {
                                            fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        } else {
                                            //向WMS下发空箱入库申请储位
//                                        ReturnVo returnVo1 = wcsReportService.emptyContainer(storageRegion);
                                            InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                            inboundStorageApplyDto.setContainerCode(palletCode);
                                            inboundStorageApplyDto.setFloor(TaskType.TWO_FLOOR.getMessage());
                                            inboundStorageApplyDto.setNest(false);
                                            inboundStorageApplyDto.setData(null);
                                            String destinatin = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                            if (destinatin != null) {
                                                //生成入库任务
                                                WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                wcsInboundMission.setContainerCode(palletCode);
                                                wcsInboundMission.setSource(storageCode);
                                                wcsInboundMission.setDestination(destinatin);
                                                wcsInboundMission.setContainerType(TaskType.WORKBIN.getStatus());
                                                wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                                wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                wcsInboundMission.setPriority(90);
                                                wcsInboundMission.setIsNest(0);
                                                wcsInboundMission.setIsPlc(1);
                                                boolean b1 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                if (!b1) {
                                                    fluentFrame.error("创建空箱入库任务失败");
                                                    throw new RuntimeException("创建空箱入库任务失败");
                                                }
                                                //往plc写入ok
                                                fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                            } else {
                                                fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                            }
                                        }

                                    }
                                } else if (mode == 1) {
                                    WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                    InboundIsCodeExistDto inboundIsCodeExist = new InboundIsCodeExistDto();
                                    if (wcsFluentFrameOutboundDetails != null) {
                                        inboundIsCodeExist.setNest(true);
                                    } else {
                                        inboundIsCodeExist.setNest(false);
                                    }
                                    //1.发送wms查看栈板是否已入库
                                    inboundIsCodeExist.setContainerCode(palletCode);
                                    inboundIsCodeExist.setNest(false);
                                    boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExist);
                                    if (b) {
                                        fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    } else {
                                        //2.查询嵌套信息是否嵌套
//                                        ReturnVo returnVo = wcsReportService.middleNestingData(palletCode);
                                        List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(palletCode);
                                        if (nestingMiddleTables.isEmpty()) {
                                            fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        } else {
                                            long rawMaterialsQ = nestingMiddleTables.stream().filter(f -> f.getMaterial().equals(TaskType.MATERIAL_Q.getMessage())).count();
                                            //判断是否自检
                                            long rawMaterialsQQualified = nestingMiddleTables.stream().filter(f -> f.getMaterial().equals(TaskType.MATERIAL_Q.getMessage()) && f.getSelfCheckStatus() == 1).count();
                                            //3.查询物料是否是原物料Q
                                            if (rawMaterialsQ != 0) {
                                                //判断是否自检
                                                if (rawMaterialsQ == rawMaterialsQQualified) {
                                                    //4.对比MES信息和WMS库存信息是否一致
                                                    TestVo testVo = wcsReportService.wmsInventoryInformation(palletCode);
                                                    if (testVo.getCode() != 200) {
                                                        fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                    } else {
                                                        //对比库存信息 对比物料条码和数量
//                                                        ArrayList<MiddleTable> mesMiddleTableList = (ArrayList<MiddleTable>) returnVo.getData();
                                                        List<MaterialDao> materialDaoList = testVo.getData();
                                                        HashSet<InventoryContrast> mesInventorySet = new HashSet<>();
                                                        HashSet<InventoryContrast> wmsInventorySet = new HashSet<>();
//                                                        BeanUtils.copyProperties(nestingMiddleTables, mesInventorySet);
//                                                        BeanUtils.copyProperties(wmsInventoryList, wmsInventorySet);
                                                        for (MaterialDao datum : materialDaoList) {
                                                            InventoryContrast wmsInventory = new InventoryContrast();
                                                            BeanUtils.copyProperties(datum, wmsInventory);
                                                            wmsInventorySet.add(wmsInventory);
                                                        }
                                                        for (NestingMiddleTable middleTable : nestingMiddleTables) {
                                                            InventoryContrast wmsInventory = new InventoryContrast();
                                                            BeanUtils.copyProperties(middleTable, wmsInventory);
                                                            mesInventorySet.add(wmsInventory);
                                                        }
                                                        if (!mesInventorySet.equals(wmsInventorySet)) {
                                                            //WMS和WES库存信息不一致
                                                            fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                        } else {
                                                            //向WMS申请终点储位
                                                            //todo　中间表查询栈板信息
                                                            InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                                            inboundStorageApplyDto.setContainerCode(palletCode);
                                                            //查询入库明细表，是否回库
//                                                            WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                                            if (wcsFluentFrameOutboundDetails != null) {
                                                                inboundStorageApplyDto.setNest(true);
                                                            } else {
                                                                inboundStorageApplyDto.setNest(false);
                                                            }
                                                            inboundStorageApplyDto.setFloor(TaskType.ONE_FLOOR.getMessage());
                                                            List<NestingMiddleTable> nestingMiddleTables1 = nestingMiddleTableService.selectContainerCode(palletCode);
                                                            ArrayList<MaterialDao> materialDaos = new ArrayList<>();
                                                            for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables1) {
                                                                MaterialDao materialDao = new MaterialDao();
                                                                BeanUtils.copyProperties(nestingMiddleTable, materialDao);
                                                                materialDaos.add(materialDao);
                                                            }
                                                            inboundStorageApplyDto.setData(materialDaos);
                                                            String destinationStorageCode = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                                            if (destinationStorageCode != null) {
                                                                WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                                if (wcsFluentFrameOutboundDetails != null) {
                                                                    //删除入库明细表，写入历史表
                                                                    WcsFluentFrameOutboundDetailsHistory wcsFluentFrameOutboundDetailsHistory = new WcsFluentFrameOutboundDetailsHistory();
                                                                    BeanUtils.copyProperties(wcsFluentFrameOutboundDetails, wcsFluentFrameOutboundDetailsHistory);
                                                                    wcsFluentFrameOutboundDetailsHistory.setId(null);
                                                                    boolean b1 = wcsFluentFrameOutboundDetailsHistoryService.insertFluentFrameOutboundDetailsHistory(wcsFluentFrameOutboundDetailsHistory);
                                                                    wcsFluentFrameOutboundDetailsService.deleteId(wcsFluentFrameOutboundDetails.getId());
                                                                    wcsInboundMission.setIsNest(1);
                                                                    wcsInboundMission.setInboundType(TaskType.circle_library_sorting.getStatus());
                                                                } else {
                                                                    wcsInboundMission.setIsNest(0);
                                                                    wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                                }
                                                                //生成入库任务
                                                                wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                                wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                                wcsInboundMission.setContainerCode(palletCode);
                                                                wcsInboundMission.setSource(storageCode);
                                                                wcsInboundMission.setDestination(destinationStorageCode);
                                                                wcsInboundMission.setContainerType(TaskType.WORKBIN.getStatus());
                                                                wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                                wcsInboundMission.setUpdateTime(LocalDateTime.now());

                                                                wcsInboundMission.setPriority(90);
                                                                wcsInboundMission.setIsPlc(1);
                                                                StringBuilder sb = new StringBuilder();
                                                                List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                                                                for (String materialCode : materialCodeList) {
                                                                    if (sb.length() > 0) {
                                                                        sb.append(",");
                                                                    }
                                                                    sb.append(materialCode);
                                                                }
                                                                wcsInboundMission.setIsPlc(1);

                                                                boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                                if (!b2) {
                                                                    fluentFrame.error("创建空箱入库任务失败");
                                                                    throw new RuntimeException("创建空箱入库任务失败");
                                                                }
                                                                //库存一至
                                                                fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                            } else {
                                                                fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                            }
                                                        }
                                                    }
                                                } else {
                                                    //自检不通过
                                                    fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_QUALITY_TESTING_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                }
                                            } else {
                                                //4.对比MES信息和WMS库存信息是否一致
                                                TestVo testVo = wcsReportService.wmsInventoryInformation(palletCode);
                                                if (testVo.getCode() != 200) {
                                                    fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                } else {
                                                    //对比库存信息 对比物料条码和数量
//                                                    ArrayList<MiddleTable> mesMiddleTableList = (ArrayList<MiddleTable>) returnVo.getData();
                                                    List<MaterialDao> materialDaoList = testVo.getData();
                                                    HashSet<InventoryContrast> mesInventorySet = new HashSet<>();
                                                    HashSet<InventoryContrast> wmsInventorySet = new HashSet<>();
                                                    for (MaterialDao datum : materialDaoList) {
                                                        InventoryContrast wmsInventory = new InventoryContrast();
                                                        BeanUtils.copyProperties(datum, wmsInventory);
                                                        wmsInventorySet.add(wmsInventory);
                                                    }
                                                    for (NestingMiddleTable middleTable : nestingMiddleTables) {
                                                        InventoryContrast wmsInventory = new InventoryContrast();
                                                        BeanUtils.copyProperties(middleTable, wmsInventory);
                                                        mesInventorySet.add(wmsInventory);
                                                    }
                                                    if (!mesInventorySet.equals(wmsInventorySet)) {
                                                        //WMS和WES库存信息不一致
                                                        fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                    } else {
                                                        //向WMS申请终点储位
                                                        InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                                        inboundStorageApplyDto.setContainerCode(palletCode);
                                                        //查询入库明细表，是否回库
//                                                        WcsFluentFrameOutboundDetails wcsFluentFrameOutboundDetails = wcsFluentFrameOutboundDetailsService.selectContainerCode(palletCode);
                                                        if (wcsFluentFrameOutboundDetails != null) {
//                                                            Integer isNest = wcsFluentFrameOutboundDetails.getIsNest();
                                                            inboundStorageApplyDto.setNest(true);
                                                        } else {
                                                            inboundStorageApplyDto.setNest(false);
                                                        }
                                                        inboundStorageApplyDto.setFloor(TaskType.ONE_FLOOR.getMessage());
                                                        List<NestingMiddleTable> nestingMiddleTables1 = nestingMiddleTableService.selectContainerCode(palletCode);
                                                        ArrayList<MaterialDao> materialDaos = new ArrayList<>();
                                                        for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables1) {
                                                            MaterialDao materialDao = new MaterialDao();
                                                            BeanUtils.copyProperties(nestingMiddleTable, materialDao);
                                                            materialDaos.add(materialDao);
                                                        }
                                                        inboundStorageApplyDto.setData(materialDaos);
                                                        String destinationStorageCode = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                                        if (destinationStorageCode != null) {
                                                            WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                            if (wcsFluentFrameOutboundDetails != null) {
                                                                //删除入库明细表，写入历史表
                                                                WcsFluentFrameOutboundDetailsHistory wcsFluentFrameOutboundDetailsHistory = new WcsFluentFrameOutboundDetailsHistory();
                                                                BeanUtils.copyProperties(wcsFluentFrameOutboundDetails, wcsFluentFrameOutboundDetailsHistory);
                                                                wcsFluentFrameOutboundDetailsHistory.setId(null);
                                                                boolean b1 = wcsFluentFrameOutboundDetailsHistoryService.insertFluentFrameOutboundDetailsHistory(wcsFluentFrameOutboundDetailsHistory);
                                                                wcsFluentFrameOutboundDetailsService.deleteId(wcsFluentFrameOutboundDetails.getId());
                                                                wcsInboundMission.setIsNest(1);
                                                                wcsInboundMission.setInboundType(TaskType.circle_library_sorting.getStatus());
                                                            } else {
                                                                wcsInboundMission.setIsNest(0);
                                                                wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                            }
                                                            //生成入库任务
                                                            wcsInboundMission.setInboundCode(String.valueOf(idWorker.nextId()));
                                                            wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                            wcsInboundMission.setContainerCode(palletCode);
                                                            wcsInboundMission.setSource(storageCode);
                                                            wcsInboundMission.setDestination(destinationStorageCode);
                                                            wcsInboundMission.setContainerType(TaskType.WORKBIN.getStatus());
                                                            wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                            wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                                            wcsInboundMission.setPriority(90);
                                                            wcsInboundMission.setIsPlc(1);
                                                            StringBuilder sb = new StringBuilder();
                                                            List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                                                            for (String materialCode : materialCodeList) {
                                                                if (sb.length() > 0) {
                                                                    sb.append(",");
                                                                }
                                                                sb.append(materialCode);
                                                            }
                                                            boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                            if (!b2) {
                                                                fluentFrame.error("创建空箱入库任务失败");
                                                                throw new RuntimeException("创建空箱入库任务失败");
                                                            }
                                                            //库存一至
                                                            fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                        } else {
                                                            fluentFrameTCPA.writeWithRetry(sortingResultAddress, MaterialStatus.RETURN_ONE_RESULT_STORAGE_LOCATION_NOT_FOUND.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }


                                }
                            }
                        }
                        //更具第三段储位查询载具号，下发任务
                        Integer inboundThreeAddress = wcsFluentFrameConfig.getInboundThreeAddress();
                        Integer inboundThreeAddressStatus = fluentFrameTCPA.readHoldingRegisters(inboundThreeAddress, unitId);
                        if (Objects.equals(inboundThreeAddressStatus, MaterialStatus.MATERIAL_STATUS_YES.getStatus())) {
                            //有料获取读码结果
                            Integer threeReadAddress = wcsFluentFrameConfig.getThreeReadAddress();
                            String palletCode = fluentFrameTCPA.readHoldingRegistersString(threeReadAddress, unitId);
                            //下发任务给AGV，修改任务状态
                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(palletCode);
                            if (!wcsInboundMissionList.isEmpty()) {
                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                                //储位绑定栈板
                                CarrierUnbindDto carrierUnbindDto = new CarrierUnbindDto();
                                carrierUnbindDto.setSlotCategory(TaskType.SITE.getMessage());
                                carrierUnbindDto.setSlotCode(wcsInboundMission.getSource());
                                carrierUnbindDto.setCarrierCategory("PALLET");
                                carrierUnbindDto.setCarrierType("1");
                                carrierUnbindDto.setInvoke(TaskType.BIND.getMessage());
                                agvSendService.carrierUnbind(carrierUnbindDto);
                                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                //todo 任务类型，根据现场情况来定
                                agvTaskSubmitDto.setTaskType(TaskType.PF_FMR_COMMON.getMessage());
                                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                TargetRoute targetRoute = new TargetRoute();
                                TargetRoute targetRoutes = new TargetRoute();
                                //添加起点
                                targetRoute.setSeq(0);
                                targetRoute.setType(TaskType.SITE.getMessage());
                                targetRoute.setCode(wcsInboundMission.getSource());
                                //添加终点
                                targetRoutes.setSeq(1);
                                targetRoutes.setType(TaskType.STORAGE.getMessage());
                                targetRoutes.setCode(wcsInboundMission.getDestination());
                                targetRouteList.add(targetRoute);
                                targetRouteList.add(targetRoutes);
                                agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                agvTaskSubmitDto.setRobotTaskCode(wcsInboundMission.getInboundCode());
                                agvTaskSubmitDto.setInitPriority(99);
                                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                if (taskCode != null) {
                                    fluentFrameTCPA.writeWithRetry(threeReturnResult, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    boolean b1 = wcsInboundMissionService.updateMissionStatus(wcsInboundMission.getInboundCode(), TaskStatus.task_send.getStatus());
                                    if (!b1) {
                                        fluentFrame.error("数据回滚，流利架下发agv任务，修改数据库失败");
                                        throw new RuntimeException("数据回滚，流利架下发agv任务，修改数据库失败");
                                    }
                                }
                            }
                        }
                    } else if (TaskType.FLUENT_FRAME_B.getMessage().equals(region)) {
                        //todo B从A复制过来就行
                    }
                }
            }
        }
    }
}
